import React, { Component } from "react";
import {
  Button,
  message,
  Modal,
  Table,
  Divider,
  Checkbox,
  Form,
  notification,
} from "antd";
import { InfoCircleTwoTone } from "@ant-design/icons";
import { importsExcel } from "./InOutExcel";
import axios from "axios";
import qs from "qs";
import importExcelDatas from "../mock/importExcelDatas";

export default class ImportExportExcel extends Component {
  // formRef = React.createRef();

  constructor(props) {
    super(props);
    this.state = {
      addVisible: false,
      confirmLoading: false,
      dataSource: [],
      selVisible: false,
      selConfirmLoading: false,
      selNameForm: "",
      needSelMeeting: [],
    };
    // 模板下载事件
    this.jumpTo = this.jumpTo.bind(this);
    this.formRefArr = [];
    this.columns = [
      {
        title: "日期",
        dataIndex: "meetingDate",
        key: "meetingDate",
        width: 120,
      },
      {
        title: "时间",
        dataIndex: "meetingTime",
        key: "meetingTime",
        width: 100,
      },
      {
        title: "地点",
        dataIndex: "locale",
        key: "locale",
        width: 150,
      },

      {
        title: "内容",
        dataIndex: "theme",
        key: "theme",
      },
      {
        title: "主持人",
        dataIndex: "host",
        key: "host",
        width: 120,
      },
      {
        title: "参加人",
        dataIndex: "participator",
        key: "participator",
        ellipsis: true,
        width: 200,
      },
    ];
  }
  showAddModal = () => {
    this.setState({
      addVisible: true,
    });
  };

  //   模板下载;
  jumpTo() {
    window.open(this.props.templateHref);
  }

  // 导出Excel表格
  exportExcel() {
    const url = this.props.downloadUrl;
    window.open(url);
  }
  /**处理表格数据 */
  getExcelData = (e) => {
    importsExcel(e).then(
      (data) => {
        // console.log(data);
        let item = {};
        let excel = data.map((line) => {
          item = { ...item, ...line };
          return {
            meetingDate: item.日期,
            meetingTime: item.时间,
            locale: item.地点,
            theme: item.内容,
            host: item.主持人,
            participator: item.参加人.replaceAll("、", ",").replaceAll(" ", ""),
          };
        });
        // console.log(excel);
        this.setState({ dataSource: excel });
        // actionList(data);
      },
      function (data) {
        console.log(data);
      }
    );
  };

  /**取消导入，关闭对话框 */
  handleCancel = () => {
    /**清空修改表单状态 */
    this.setState({
      addVisible: false,
      dataSource: [],
      confirmLoading: false,
    });
  };

  /**确认导入 */
  uploadExcel = () => {
    /**导入表格 */
    if (this.state.dataSource.length) {
      this.setState({
        confirmLoading: true,
      });
      axios
        .post(
          "importExcelDatas.rst",
          qs.stringify({ data: JSON.stringify(this.state.dataSource) })
        )
        .then((res) => {
          let response = res.data;
          // console.log(response);
          if (response.resultCode === 0) {
            let data = response.result.data;
            if (data.length === 0) {
              /**没有重名 */
              this.setState({
                confirmLoading: false,
                addVisible: false,
              });
              message.success("数据导入成功");
              this.props.getDataSource();
            } else {
              /**开始重名选择 */
              /**渲染数据 */
              this.showSelNameForm(data);
            }
          } else {
            if (response.errorMsg.indexOf("不在规定的人员列表中")) {
              message.error(
                response.errorMsg.substring(
                  response.errorMsg.lastIndexOf("Exception:") + 11
                )
              );
              // notification.error({
              //   message: "数据导入时出错",
              //   description: response.errorMsg.substring(
              //     response.errorMsg.lastIndexOf("Exception:") + 11
              //   ),
              // });
            } else {
              message.error("数据导入失败");
            }
          }
        })
        .catch((error) => {
          message.error("数据导入失败");
        });
    } else {
      message.warning("请先上传表格");
    }
  };
  /**重名选择界面 */
  showSelNameForm = (data) => {
    this.setState({
      needSelMeeting: data.map((meeting) => {
        return [meeting.meetingId];
      }),
      selNameForm: data.map((meeting, i) => {
        // console.log(meeting);
        return (
          <>
            <Divider />
            <div className="the-meeting">
              <div className="meeting-info">
                会议主题：<span>{meeting.theme}</span>
              </div>
              <div className="meeting-info">
                日期：<span>{meeting.meetingDate}</span>
              </div>
              <div className="meeting-info">
                时间：<span>{meeting.meetingTime}</span>
              </div>
              <div className="meeting-info">
                地点：<span>{meeting.locale}</span>
              </div>

              <div>指定参会人：</div>
              <div className="meeting-sel">
                <Form
                  ref={(this.formRefArr[i] = React.createRef())}
                  name={meeting.theme}
                  preserve={false}
                >
                  {meeting.users.map((name, k) => {
                    let isHost = name.isHost ? "/" : "";
                    return (
                      <>
                        {/* <div className="name-select">{name.name}：</div> */}
                        <Form.Item
                          key={k}
                          name={name.name + isHost}
                          label={name.name}
                          valuePropName={name.name}
                          className="sel-name"
                        >
                          <Checkbox.Group>
                            {name.userInfos.map((userInfos, j) => {
                              return (
                                <Checkbox
                                  key={j}
                                  value={userInfos.id}
                                  className="sel-option"
                                >
                                  <span className="select-field">
                                    ID：{userInfos.id}
                                  </span>
                                  <span className="select-field">
                                    年龄：{userInfos.age}
                                  </span>
                                  <span className="select-field">
                                    性别：{userInfos.sex}
                                  </span>
                                </Checkbox>
                              );
                            })}
                          </Checkbox.Group>
                        </Form.Item>
                      </>
                    );
                  })}
                </Form>
              </div>
            </div>
          </>
        );
      }),
      /**打开重名对话框 */
      selVisible: true,
    });
  };

  /**发送重名选择结果 */
  sendSel = (value) => {
    let result = this.formRefArr.map((refitem, index) => {
      let val = refitem.current.getFieldsValue(true);
      let people = "";
      for (var key in val) {
        val[key].map((id) => {
          people += "," + id + "_" + key;
        });
      }
      return {
        meetingId: this.state.needSelMeeting[index][0],
        selectedUser: people.substr(1),
      };
    });

    /**提交筛选结果 */
    // console.log(result);筛选结果
    axios
      .post(
        "duplicateNameResult.rst",
        qs.stringify({
          data: JSON.stringify(result),
        })
      )
      .then((res) => {
        let response = res.data;
        console.log(response);
        if (response.resultCode === 0) {
          message.success("数据导入成功");
          this.props.getDataSource();
          setTimeout(() => {
            this.setState({
              selVisible: false,
              addVisible: false,
              selNameForm: "",
              dataSource: [],
              needSelMeeting: [],
              confirmLoading: false,
              selConfirmLoading: false,
            });
          }, 0);
          this.formRefArr = [];
        } else {
          message.error("数据导入失败");
        }
      })
      .catch((error) => {
        console.log(error);
        message.error("数据导入失败");
        setTimeout(() => {
          this.setState({
            selVisible: false,
            addVisible: false,
            selNameForm: "",
            dataSource: [],
            needSelMeeting: [],
            confirmLoading: false,
            selConfirmLoading: false,
          });
        }, 0);
        this.formRefArr = [];
      });
  };

  render() {
    const {
      addVisible,
      selVisible,
      dataSource,
      confirmLoading,
      selConfirmLoading,
      selNameForm,
    } = this.state;
    return (
      <>
        {/* <Button type="primary" key="exportExcel" onClick={this.exportExcel}>
          导出
        </Button> */}
        <Button type="primary" onClick={this.showAddModal}>
          导入
        </Button>
        <Modal
          /**对话框属性 */
          visible={addVisible}
          title="导入会议"
          centered
          onCancel={this.handleCancel}
          width={1000}
          height={500}
          onOk={this.uploadExcel}
          confirmLoading={confirmLoading}
          okText="导入"
          cancelText="取消"
          destroyOnClose={true}
          keyboard={false}
          className="edit-modal import"
        >
          <input
            type="file"
            accept=".xls,.xlsx"
            onChange={(e) => {
              this.getExcelData(e);
            }}
          />
          <InfoCircleTwoTone style={{ fontSize: "21px", margin: "7px" }} />
          <span>如预览中数据有误，请检查字段后再重新上传</span>
          <Divider />
          <p>
            注：为避免识别错误，需要将首行表头字段固定为：日期、时间、地点、内容、主持人、参加人，几个字段。
            日期字段格式为 yyyy-mm-dd ，月份不满10的需补‘0’，避免使用中文字符。
            时间字段格式为 HH:MM ，使用24小时制，避免使用中文字符。
            多个参加人使用中文顿号“、”分隔。
            单元格无数据时请填入空格或者“无”，避免留空
          </p>
          <Table
            dataSource={dataSource}
            columns={this.columns}
            bordered
            scroll={{ y: 280 }}
            pagination={false}
          />
          <Modal
            /**对话框属性 */
            visible={selVisible}
            title="重名筛选"
            centered
            width={900}
            okText="确认"
            destroyOnClose={true}
            /**阻止关闭 */
            maskClosable={false}
            keyboard={false}
            closable={false}
            className="edit-modal import"
            footer={[
              <Button
                key="submit"
                type="primary"
                loading={selConfirmLoading}
                onClick={this.sendSel}
              >
                保存
              </Button>,
            ]}
          >
            <InfoCircleTwoTone style={{ fontSize: "21px", margin: "7px" }} />
            <span>
              您刚刚导入的会议中的参会人或主持人信息在职工数据中有重名的情况，请做进一步确认
            </span>
            {selNameForm}
          </Modal>
        </Modal>
      </>
      // <Button style={{marginLeft: 10}} key='templateDowload' onClick={this.jumpTo}>模板下载</Button>
    );
  }
}

// // 定义参数类型
// ImportExportExcel.propTypes = {
//   // 模板下载地址
//   // templateHref: PropTypes.string.isRequired,
//   // 上传地址
//   url: PropTypes.string.isRequired,
//   // 导入成功后的回调
//   importSuccessCallback: PropTypes.func,
// };
